package com.token.sysflow.service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.token.base.Pl;
import com.token.sql.IntegrateSql;
import com.token.sql.TableBeanPrepareSql;
import com.token.sysapp.bean.FSysAppInfo;

import java.sql.ResultSet;

/**
 * @author chenjianxiong 2020/4/28
 */
public class AppSelectTree {
    TableBeanPrepareSql tSql;
    JSONArray flowType;

    /**
     * @param f
     * @throws Exception
     */
    public AppSelectTree(IntegrateSql f) throws Exception {
        tSql = new TableBeanPrepareSql(new FSysAppInfo(f));
        flowType = MultDataItem.readData(f, "MV_FlowType");
    }

    /**
     * selectTree 结构
     * @return
     * @throws Exception
     */
    public JSONArray getAppSelectTreeData() throws Exception{
        JSONArray array = new JSONArray();
        JSONObject jsonObject;
        for(int i=0;i<flowType.size();i++){
            jsonObject = flowType.getJSONObject(i);
            jsonObject.put("id",jsonObject.getString("value"));
            jsonObject.put("pId", "");
            jsonObject.put("selectable", false);
            jsonObject.put("key", jsonObject.getString("value"));
            array.add(jsonObject);
        }

        readAllUseAppSelectTreeData(array);
        return array;
    }

    /**
     *
     * @throws Exception
     */
    private void readAllUseAppSelectTreeData(JSONArray array) throws Exception{
        tSql.setSelectPrepare("SysId=? and IsUse=1");
        tSql.setPstValue(1, Pl.getSysId());
        ResultSet rs = tSql.executeQuery();
        if (rs.next()) {
            JSONObject json;
            do {
                json = new JSONObject();
                json.put("id", rs.getString("AppKeyId"));
                json.put("pId", rs.getString("FlowType"));
                json.put("value", rs.getString("AppKeyId"));
                json.put("title", rs.getString("AppDesc"));
                json.put("key", rs.getString("AppKeyId"));
                json.put("isLeaf", true);
                array.add(json);
            } while (rs.next());
        }
        rs.close();
    }

    public void close(){
        flowType = null;
        tSql.close();
    }
}
